package cn.ydxiaoshuai.modules.liteuser.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.ydxiaoshuai.common.util.DateUtils;
import cn.ydxiaoshuai.modules.liteuser.entity.LiteUserInfo;
import cn.ydxiaoshuai.modules.liteuser.mapper.LiteUserInfoMapper;
import cn.ydxiaoshuai.modules.liteuser.service.ILiteUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

/**
 * @Description: 微信用户信息表
 * @Author: 小帅丶
 * @Date:   2020-05-14
 * @Version: V1.0
 */
@Service
@Slf4j
public class LiteUserInfoServiceImpl extends ServiceImpl<LiteUserInfoMapper, LiteUserInfo> implements ILiteUserInfoService {
    @Autowired
    private LiteUserInfoMapper liteUserInfoMapper;

    @Override
    public List<LiteUserInfo>  getByUserId(String userId){
        return liteUserInfoMapper.getByUserId(userId);
    }

    @Override
    public void updateByUserId(String userId, String nickName, String avatarUrl, String phoneNum) {
        liteUserInfoMapper.updateByUserId(userId,nickName,avatarUrl,phoneNum);
    }

    @Override
    public void updateUserDays() {
        //当前日期
        String toDay = DateUtil.today();
        log.info("当前日期:{}",toDay);
        LambdaQueryWrapper<LiteUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(LiteUserInfo::getCreateTime,LiteUserInfo::getDays,LiteUserInfo::getId,LiteUserInfo::getUserId);
        queryWrapper.isNotNull(LiteUserInfo::getCreateTime);
        long startTime = System.currentTimeMillis();
        List<LiteUserInfo> liteUserInfos = liteUserInfoMapper.selectList(queryWrapper);
        if(liteUserInfos.size()>0){
            log.info("需要同步的用户:{}",liteUserInfos.size());
            liteUserInfos.forEach(liteUserInfo -> {
                LiteUserInfo liteUserInfoDB = liteUserInfo;
                String registeDate = DateUtil.format(liteUserInfoDB.getCreateTime(), DatePattern.NORM_DATE_PATTERN);
                int Days = DateUtils.caculateTotalTime(toDay,registeDate);
                liteUserInfoDB.setDays(Days);
                liteUserInfoMapper.updateById(liteUserInfoDB);
            });
            long endTime = System.currentTimeMillis();
            log.info("天数更新耗时(ms):{}",(endTime-startTime));
        }
    }
}
